package com.dp.appi.controller;

import com.dp.appi.entity.UserEntity;
import com.dp.appi.exception.CommonException;
import com.dp.appi.exception.PackageRuntimeException;
import com.dp.appi.service.PhotoService;
import com.dp.appi.service.SysConfigService;
import com.dp.appi.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by chenghao on 2015/9/30.
 */
@Controller
@RequestMapping(value = "/photoControl")
public class PhotoControl {

    private static Logger log = LoggerFactory.getLogger(ConsumerControl.class);

    @Value("${offline_photo_upload_path}")
    private String offline_photo_upload_path;//离线包上传路径
    @Value("${offline_problem_upload_path}")
    private String offline_problem_upload_path;
    @Autowired
    private PhotoService photoService;

    @RequestMapping(value = "/recordAndPhotoList", method = RequestMethod.POST)
    public void recordAndPhotoList(ModelMap modelMap, @RequestParam Map<String, String> param) {
        try {
            String stageid = param.get("stageid");
            String lasttimestr = param.get("lasttime").toString();
            if(lasttimestr.equals(""))
            {
                lasttimestr="10000";
            }
            if(!stageid.equals("")) {
                Long lasttime = Long.parseLong(lasttimestr);
                List<Map<String, Object>> listre = photoService.getRecordProject(Long.parseLong(stageid),lasttime);
                List<Map<String, Object>> listph = photoService.getPhoneProject(Long.parseLong(stageid),lasttime);

                modelMap.addAttribute("recordList", listre);
                modelMap.addAttribute("photoList", listph);
            }
            else
            {
                modelMap.addAllAttributes(SYS.E10003.msgMap());
            }

        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
        }
    }

    /**
     * 离线上传
     *
     * @param modelMap 返回数据
     * @param param    提交参数
     * @param request  请求对象
     * @param file     离线压缩包
     */
    @RequestMapping(value = "/offlinePhotoUpload", method = RequestMethod.POST)
    public void offlinePhotoUpload(ModelMap modelMap, @RequestParam Map<String, String> param,
                              HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        try {
            String stageId =param.get("stage_id");

            //判断目录是否存在 不存在创建
            String _path = offline_photo_upload_path + DateUtil.getNowDateStr() + "/";
            File f = new File(_path);
            if (!f.exists()) {
                f.mkdirs();
            }

            String filename = file.getOriginalFilename();
            File targetFile = new File(_path + filename);
            //是文件且存在,存在文件
            Integer classify = null;

            String[] _files = filename.split("\\.");
            String suffix = _files[1];//后缀
            String prefix = _files[0];//前缀
//            targetFile.isFile() && targetFile.exists()
            if (targetFile.exists()) {
                FileUtil fileUtil = new FileUtil();
                fileUtil.deleteFile(_path + filename);//删除已经存在的压缩文件
                fileUtil.deleteDirectory(_path + prefix);//删除解压后的压缩文件路径
            }
            //上传文件
            file.transferTo(targetFile);
            //解压
            CompressFile.unZipFiles(targetFile, _path);


            //遍历文件夹,成功后返回阶段id
            Long stage_id = photoService.analysisPackage(_path + prefix,stageId);



            //数据处理完毕后重新打包返回数据包给客户端

            modelMap.addAttribute(SYS.SUCCESS.msgMap());


        } catch (PackageRuntimeException e) {
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
            e.printStackTrace();
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
            e.printStackTrace();
        }
    }
    //验收缺陷照片
    @RequestMapping(value = "/offlineProblemUpload", method = RequestMethod.POST)
    public void offlineProblemUpload(ModelMap modelMap, @RequestParam Map<String, String> param,
                                   HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        try {
            String stageId =param.get("stage_id");

            //判断目录是否存在 不存在创建
            String _path = offline_problem_upload_path  + DateUtil.getNowDateStr() + "/";
            File f = new File(_path);
            if (!f.exists()) {
                f.mkdirs();
            }

            String filename = file.getOriginalFilename();
            File targetFile = new File(_path + filename);
            //是文件且存在,存在文件
            Integer classify = null;

            String[] _files = filename.split("\\.");
            String suffix = _files[1];//后缀
            String prefix = _files[0];//前缀
//            targetFile.isFile() && targetFile.exists()
            if (targetFile.exists()) {
                FileUtil fileUtil = new FileUtil();
                fileUtil.deleteFile(_path + filename);//删除已经存在的压缩文件
                fileUtil.deleteDirectory(_path + prefix);//删除解压后的压缩文件路径
            }
            //上传文件
            file.transferTo(targetFile);
            //解压
            CompressFile.unZipFiles(targetFile, _path);


            //遍历文件夹,成功后返回阶段id
            Long stage_id = photoService.analysisPackageproblem (_path + prefix,stageId);



            //数据处理完毕后重新打包返回数据包给客户端

            modelMap.addAttribute(SYS.SUCCESS.msgMap());


        } catch (PackageRuntimeException e) {
            modelMap.addAllAttributes(SYS.valueOf(e.getMessage()).msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
            e.printStackTrace();
        } catch (Exception e) {
            modelMap.addAllAttributes(SYS.E10002.msgMap());
            log.error(ExceptionUtil.getExceptionAllinformation(e));
            e.printStackTrace();
        }
    }


}
